<!--
  智慧社区管理系统 - 充电桩管理 (静态展示页面)
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
    <div class="charging-pile-container">
        <!-- 页面标题 -->
        <el-card class="title-card">
            <div class="page-header">
                <h2>⚡ 充电桩管理</h2>
                <p class="page-description">管理社区内所有充电桩信息，包括充电桩配置、状态监控、充电记录等功能</p>
            </div>
        </el-card>

        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" inline>
                <el-form-item label="充电桩编号">
                    <el-input v-model="searchForm.pileNo" placeholder="请输入充电桩编号" clearable />
                </el-form-item>
                <el-form-item label="充电桩类型">
                    <el-select v-model="searchForm.pileType" placeholder="请选择充电桩类型" clearable>
                        <el-option label="快充" :value="1" />
                        <el-option label="慢充" :value="2" />
                        <el-option label="超充" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                        <el-option label="空闲" :value="0" />
                        <el-option label="充电中" :value="1" />
                        <el-option label="故障" :value="2" />
                        <el-option label="维护" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 统计信息卡片 -->
        <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon success">
                            <el-icon><Lightning /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.total }}</div>
                            <div class="stats-label">总充电桩数</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon primary">
                            <el-icon><CircleCheck /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.available }}</div>
                            <div class="stats-label">空闲充电桩</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon warning">
                            <el-icon><Loading /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.charging }}</div>
                            <div class="stats-label">充电中</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon danger">
                            <el-icon><Warning /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.faulty }}</div>
                            <div class="stats-label">故障充电桩</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 操作区域 -->
        <el-card class="operation-card">
            <el-button type="primary" @click="handleAdd">添加充电桩</el-button>
            <el-button type="success" @click="handleBatchAdd">批量添加</el-button>
            <el-button type="warning" @click="handleRefresh">刷新</el-button>
            <el-button type="info" @click="handleExport">导出数据</el-button>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card">
            <el-table :data="filteredTableData" border v-loading="loading" stripe>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="pileNo" label="充电桩编号" width="120" />
                <el-table-column prop="pileTypeName" label="充电桩类型" width="100" />
                <el-table-column prop="power" label="功率(kW)" width="100" />
                <el-table-column prop="voltage" label="电压(V)" width="100" />
                <el-table-column prop="current" label="电流(A)" width="100" />
                <el-table-column prop="statusName" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">{{ row.statusName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="licensePlate" label="车牌号" width="120" />
                <el-table-column prop="startTime" label="开始时间" width="180" />
                <el-table-column prop="duration" label="充电时长" width="100" />
                <el-table-column prop="energy" label="充电量(kWh)" width="120" />
                <el-table-column prop="fee" label="费用" width="100">
                    <template #default="{ row }">
                        ¥{{ row.fee || '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="success" size="small" @click="handleStartCharging(row)" v-if="row.status === 0">开始充电</el-button>
                        <el-button type="warning" size="small" @click="handleStopCharging(row)" v-if="row.status === 1">停止充电</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="600px"
            @close="handleDialogClose"
        >
            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="充电桩编号" prop="pileNo">
                            <el-input v-model="form.pileNo" placeholder="请输入充电桩编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="充电桩类型" prop="pileType">
                            <el-select v-model="form.pileType" placeholder="请选择充电桩类型" style="width: 100%">
                                <el-option label="快充" :value="1" />
                                <el-option label="慢充" :value="2" />
                                <el-option label="超充" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="功率(kW)" prop="power">
                            <el-input-number v-model="form.power" :min="1" :max="500" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电压(V)" prop="voltage">
                            <el-input-number v-model="form.voltage" :min="220" :max="1000" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="电流(A)" prop="current">
                            <el-input-number v-model="form.current" :min="1" :max="500" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                                <el-option label="空闲" :value="0" />
                                <el-option label="充电中" :value="1" />
                                <el-option label="故障" :value="2" />
                                <el-option label="维护" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="安装位置" prop="location">
                    <el-input v-model="form.location" placeholder="请输入安装位置" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>

        <!-- 开始充电对话框 -->
        <el-dialog
            v-model="chargingDialogVisible"
            title="开始充电"
            width="500px"
        >
            <el-form :model="chargingForm" :rules="chargingRules" ref="chargingFormRef" label-width="100px">
                <el-form-item label="充电桩信息">
                    <el-input :value="chargingForm.pileInfo" disabled />
                </el-form-item>
                <el-form-item label="车牌号" prop="licensePlate">
                    <el-input v-model="chargingForm.licensePlate" placeholder="请输入车牌号" />
                </el-form-item>
                <el-form-item label="车主姓名" prop="ownerName">
                    <el-input v-model="chargingForm.ownerName" placeholder="请输入车主姓名" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input 
                        v-model="chargingForm.phone" 
                        placeholder="请输入手机号码" 
                        maxlength="11"
                        show-word-limit
                    />
                </el-form-item>
                <el-form-item label="充电模式" prop="chargingMode">
                    <el-select v-model="chargingForm.chargingMode" placeholder="请选择充电模式" style="width: 100%">
                        <el-option label="自动充满" value="auto" />
                        <el-option label="定时充电" value="timer" />
                        <el-option label="按电量充电" value="energy" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="chargingDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleChargingSubmit" :loading="submitLoading">开始充电</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Lightning, CircleCheck, Loading, Warning } from '@element-plus/icons-vue'
import { showSuccess, showError } from '@/utils/message'
import { validators } from '@/utils/validate'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const chargingDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const chargingFormRef = ref<FormInstance>()

// 静态数据 - 充电桩列表
const tableData = ref([
    {
        id: 1,
        pileNo: 'CP001',
        pileType: 1,
        pileTypeName: '快充',
        power: 60,
        voltage: 380,
        current: 100,
        status: 0,
        statusName: '空闲',
        location: 'A区地下停车场',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '60kW快充桩'
    },
    {
        id: 2,
        pileNo: 'CP002',
        pileType: 1,
        pileTypeName: '快充',
        power: 60,
        voltage: 380,
        current: 100,
        status: 1,
        statusName: '充电中',
        location: 'A区地下停车场',
        licensePlate: '京C11111',
        startTime: '2024-01-15 10:30:00',
        duration: '1小时30分',
        energy: 45.5,
        fee: 45.50,
        remark: '60kW快充桩'
    },
    {
        id: 3,
        pileNo: 'CP003',
        pileType: 2,
        pileTypeName: '慢充',
        power: 7,
        voltage: 220,
        current: 32,
        status: 0,
        statusName: '空闲',
        location: 'A区地下停车场',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '7kW慢充桩'
    },
    {
        id: 4,
        pileNo: 'CP004',
        pileType: 3,
        pileTypeName: '超充',
        power: 120,
        voltage: 400,
        current: 300,
        status: 1,
        statusName: '充电中',
        location: 'C区立体车库',
        licensePlate: '京C22222',
        startTime: '2024-01-15 11:00:00',
        duration: '45分钟',
        energy: 90.0,
        fee: 90.00,
        remark: '120kW超充桩'
    },
    {
        id: 5,
        pileNo: 'CP005',
        pileType: 2,
        pileTypeName: '慢充',
        power: 7,
        voltage: 220,
        current: 32,
        status: 2,
        statusName: '故障',
        location: 'B区地面停车场',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '设备故障，待维修'
    },
    {
        id: 6,
        pileNo: 'CP006',
        pileType: 1,
        pileTypeName: '快充',
        power: 60,
        voltage: 380,
        current: 100,
        status: 3,
        statusName: '维护',
        location: 'C区立体车库',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '定期维护中'
    },
    {
        id: 7,
        pileNo: 'CP007',
        pileType: 2,
        pileTypeName: '慢充',
        power: 7,
        voltage: 220,
        current: 32,
        status: 0,
        statusName: '空闲',
        location: 'B区地面停车场',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '7kW慢充桩'
    },
    {
        id: 8,
        pileNo: 'CP008',
        pileType: 3,
        pileTypeName: '超充',
        power: 120,
        voltage: 400,
        current: 300,
        status: 0,
        statusName: '空闲',
        location: 'C区立体车库',
        licensePlate: '',
        startTime: '',
        duration: '',
        energy: 0,
        fee: 0,
        remark: '120kW超充桩'
    }
])

// 统计信息
const stats = computed(() => {
    const total = tableData.value.length
    const available = tableData.value.filter(item => item.status === 0).length
    const charging = tableData.value.filter(item => item.status === 1).length
    const faulty = tableData.value.filter(item => item.status === 2 || item.status === 3).length
    
    return { total, available, charging, faulty }
})

// 分页
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 搜索表单
const searchForm = reactive({
    pileNo: '',
    pileType: null,
    status: null
})

// 表单数据
const form = reactive({
    id: null,
    pileNo: '',
    pileType: 1,
    power: 60,
    voltage: 380,
    current: 100,
    status: 0,
    location: '',
    remark: ''
})

// 充电表单
const chargingForm = reactive({
    pileId: null,
    pileInfo: '',
    licensePlate: '',
    ownerName: '',
    phone: '',
    chargingMode: 'auto'
})

// 表单验证规则
const rules: FormRules = {
    pileNo: [{ required: true, message: '请输入充电桩编号', trigger: 'blur' }],
    pileType: [{ required: true, message: '请选择充电桩类型', trigger: 'change' }],
    power: [{ required: true, message: '请输入功率', trigger: 'blur' }],
    voltage: [{ required: true, message: '请输入电压', trigger: 'blur' }],
    current: [{ required: true, message: '请输入电流', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }]
}

const chargingRules: FormRules = {
    licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
    ownerName: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
    phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        validators.mobile('请输入正确的手机号码')
    ],
    chargingMode: [{ required: true, message: '请选择充电模式', trigger: 'change' }]
}

// 过滤后的表格数据
const filteredTableData = computed(() => {
    let filtered = [...tableData.value]
    
    if (searchForm.pileNo) {
        filtered = filtered.filter(item => item.pileNo.includes(searchForm.pileNo))
    }
    
    if (searchForm.pileType !== null) {
        filtered = filtered.filter(item => item.pileType === searchForm.pileType)
    }
    
    if (searchForm.status !== null) {
        filtered = filtered.filter(item => item.status === searchForm.status)
    }
    
    // 更新分页总数
    pagination.total = filtered.length
    
    // 分页处理
    const start = (pagination.current - 1) * pagination.size
    const end = start + pagination.size
    return filtered.slice(start, end)
})

// 获取状态类型
const getStatusType = (status: number) => {
    switch (status) {
        case 0: return 'success'
        case 1: return 'warning'
        case 2: return 'danger'
        case 3: return 'info'
        default: return 'info'
    }
}

// 搜索
const handleSearch = () => {
    pagination.current = 1
    showSuccess('搜索完成')
}

// 重置
const handleReset = () => {
    Object.assign(searchForm, {
        pileNo: '',
        pileType: null,
        status: null
    })
    pagination.current = 1
    showSuccess('重置完成')
}

// 刷新
const handleRefresh = () => {
    showSuccess('数据已刷新')
}

// 导出数据
const handleExport = () => {
    showSuccess('数据导出功能演示 - 实际开发中会生成Excel文件')
}

// 批量添加
const handleBatchAdd = () => {
    showSuccess('批量添加功能演示 - 实际开发中会批量创建充电桩')
}

// 添加
const handleAdd = () => {
    dialogTitle.value = '添加充电桩'
    Object.assign(form, {
        id: null,
        pileNo: '',
        pileType: 1,
        power: 60,
        voltage: 380,
        current: 100,
        status: 0,
        location: '',
        remark: ''
    })
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑充电桩'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除该充电桩吗？', '提示', {
            type: 'warning'
        })
        
        // 模拟删除操作
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index > -1) {
            tableData.value.splice(index, 1)
            showSuccess('删除成功')
        }
    } catch (error) {
        if (error !== 'cancel') {
            showError('删除失败')
        }
    }
}

// 开始充电
const handleStartCharging = (row: any) => {
    chargingForm.pileId = row.id
    chargingForm.pileInfo = `${row.pileNo} - ${row.pileTypeName}`
    chargingForm.licensePlate = ''
    chargingForm.ownerName = ''
    chargingForm.phone = ''
    chargingForm.chargingMode = 'auto'
    chargingDialogVisible.value = true
}

// 停止充电
const handleStopCharging = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要停止充电吗？', '提示', {
            type: 'warning'
        })
        
        // 模拟停止充电操作
        const item = tableData.value.find(item => item.id === row.id)
        if (item) {
            item.status = 0
            item.statusName = '空闲'
            item.licensePlate = ''
            item.startTime = ''
            item.duration = ''
            item.energy = 0
            item.fee = 0
            showSuccess('充电已停止')
        }
    } catch (error) {
        if (error !== 'cancel') {
            showError('操作失败')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitLoading.value = true
        
        // 模拟提交操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        if (form.id) {
            // 编辑模式
            const index = tableData.value.findIndex(item => item.id === form.id)
            if (index > -1) {
                Object.assign(tableData.value[index], {
                    ...form,
                    pileTypeName: getPileTypeName(form.pileType),
                    statusName: getStatusName(form.status)
                })
            }
            showSuccess('更新成功')
        } else {
            // 添加模式
            const newId = Math.max(...tableData.value.map(item => item.id)) + 1
            const newPile = {
                ...form,
                id: newId,
                pileTypeName: getPileTypeName(form.pileType),
                statusName: getStatusName(form.status),
                licensePlate: '',
                startTime: '',
                duration: '',
                energy: 0,
                fee: 0
            }
            tableData.value.push(newPile)
            showSuccess('添加成功')
        }
        
        dialogVisible.value = false
    } catch (error) {
        showError('提交失败')
    } finally {
        submitLoading.value = false
    }
}

// 充电提交
const handleChargingSubmit = async () => {
    if (!chargingFormRef.value) return
    
    try {
        await chargingFormRef.value.validate()
        submitLoading.value = true
        
        // 模拟开始充电操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const item = tableData.value.find(item => item.id === chargingForm.pileId)
        if (item) {
            item.status = 1
            item.statusName = '充电中'
            item.licensePlate = chargingForm.licensePlate
            item.startTime = new Date().toLocaleString()
            item.duration = '0分钟'
            item.energy = 0
            item.fee = 0
            showSuccess('充电已开始')
        }
        
        chargingDialogVisible.value = false
    } catch (error) {
        showError('操作失败')
    } finally {
        submitLoading.value = false
    }
}

// 对话框关闭
const handleDialogClose = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
}

// 当前页改变
const handleCurrentChange = (current: number) => {
    pagination.current = current
}

// 获取充电桩类型名称
const getPileTypeName = (type: number) => {
    switch (type) {
        case 1: return '快充'
        case 2: return '慢充'
        case 3: return '超充'
        default: return '快充'
    }
}

// 获取状态名称
const getStatusName = (status: number) => {
    switch (status) {
        case 0: return '空闲'
        case 1: return '充电中'
        case 2: return '故障'
        case 3: return '维护'
        default: return '空闲'
    }
}

// 初始化
onMounted(() => {
    pagination.total = tableData.value.length
})
</script>

<style scoped>
.charging-pile-container {
    padding: 20px;
}

.title-card {
    margin-bottom: 20px;
}

.page-header {
    text-align: center;
}

.page-header h2 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 24px;
}

.page-description {
    margin: 0;
    color: #909399;
    font-size: 14px;
}

.search-card {
    margin-bottom: 20px;
}

.stats-row {
    margin-bottom: 20px;
}

.stats-card {
    height: 100px;
}

.stats-content {
    display: flex;
    align-items: center;
    height: 100%;
}

.stats-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    font-size: 24px;
    color: white;
}

.stats-icon.success {
    background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stats-icon.primary {
    background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stats-icon.warning {
    background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stats-icon.danger {
    background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stats-info {
    flex: 1;
}

.stats-number {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
}

.stats-label {
    font-size: 14px;
    color: #909399;
}

.operation-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style> 